package com.dbumama.market.service.provider;

import com.dbumama.market.model.BuyerSettleInfo;
import com.dbumama.market.model.BuyerUser;
import com.dbumama.market.model.TransOrder;
import com.dbumama.market.service.api.trans.TransService;
import com.jfinal.plugin.activerecord.Db;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("transService")
public class TransServiceImpl implements TransService {

    private static final TransOrder transOrderDao = new TransOrder().dao();

    private static final BuyerSettleInfo settleInfoDao = new BuyerSettleInfo().dao();


    public String createOrder(Long buyerId, String amt) {
        String transId = createSeq("trans_order");
        TransOrder transOrder = new TransOrder();
        transOrder.setBuyerId(buyerId);
        transOrder.setTransAmt(amt);
        transOrder.setTransId(transId);
        transOrder.save();
        return transId;
    }

    @Override
    public String createOrderId(String name) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = simpleDateFormat.format(new Date());
        Integer seq = Db.queryInt("SELECT nextval(?)", name);
        String seqNo = StringUtils.leftPad(String.valueOf(seq), 6, '0');
        String orderId = date+seqNo;
        return orderId;
    }

    @Override
    public TransOrder getOrder(String trans_id) {
        return transOrderDao.findFirst("select * from t_trans_order where trans_id=? ", trans_id);
    }

    public String createSeq(String name) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
        String date = simpleDateFormat.format(new Date());
        Integer seq = Db.queryInt("SELECT nextval(?)", name);
        DecimalFormat df = new DecimalFormat("000000");
        String S = df.format(seq);
        return "TX" + date + S;
    }

    public List<BuyerSettleInfo> findSettleList(Long buyerId){

        return settleInfoDao.find("select * from t_buyer_settle_info where buyer_id=?",buyerId);
    }

    @Override
    public BuyerSettleInfo findByCardNo(String cardNo) {
        return settleInfoDao.findFirst("select * from t_buyer_settle_info where card_no=?",cardNo);
    }

    @Override
    public List<TransOrder> getOrdersByBuyerId(Long buyerId) {
        return transOrderDao.find("select * from t_trans_order where buyer_id=?",buyerId);
    }

}
